package com.example.teachingSystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.teachingSystem.mapper.SysUserMapper;
import com.example.teachingSystem.pojo.entity.ConstantEnum;
import com.example.teachingSystem.pojo.entity.SysUser;
import com.example.teachingSystem.pojo.form.user.AddUserForm;
import com.example.teachingSystem.pojo.form.user.ChangeUserInfoForm;
import com.example.teachingSystem.pojo.form.user.UserPageQuery;
import com.example.teachingSystem.pojo.vo.UserInfoVo;
import com.example.teachingSystem.service.SysUserService;
import com.example.teachingSystem.utils.JwtHelper;
import com.example.teachingSystem.utils.MD5Util;
import com.example.teachingSystem.utils.result.PageResult;
import com.example.teachingSystem.utils.result.Result;
import com.example.teachingSystem.utils.result.ResultCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author 86147
 * @description 针对表【sys_user(用户表)】的数据库操作Service实现
 * @createDate 2023-11-27 21:50:09
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
        implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private JwtHelper jwtHelper;
    @Autowired
    private HttpServletRequest request;

    @Override
    public Result<String> addUser(AddUserForm addUserForm) {
        if (sysUserMapper.exists(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, addUserForm.getUsername()))) {
            return Result.build(null, ResultCodeEnum.USERNAME_USED);
        }
        SysUser user = new SysUser();
        BeanUtils.copyProperties(addUserForm, user);
        //对密码进行加密
        user.setPassword(MD5Util.encrypt(addUserForm.getPassword()));
        if(this.save(user)){
//            if(!addUserForm.getRoleIds().isEmpty()){
//                new Thread(() -> {
//                    SysUser sysUser = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>()
//                            .eq(SysUser::getUsername,user.getUsername()));
//                    UserRoleForm userRoleForm = new UserRoleForm();
//                    userRoleForm.setUserId(sysUser.getId());
//                    userRoleForm.setRoleIds(addUserForm.getRoleIds());
//                    sysUserRoleService.addUserRoles(userRoleForm);
//                }).start();
//            }
            return Result.ok(null, "添加成功");
        }
        return Result.build(null,500,"操作失败");

    }

    @Override
    public Result<String> addUsers(List<AddUserForm> addUserFormList) {
        List<SysUser> userList = new ArrayList<>();
        for(AddUserForm item : addUserFormList){
            SysUser user = new SysUser();
            BeanUtils.copyProperties(item,user);
            user.setPassword(MD5Util.encrypt(user.getPassword()));
            userList.add(user);
        }
        this.saveBatch(userList);
        return Result.ok(null, "添加成功");
    }

    @Override
    public Result<UserInfoVo> getMineInfo() {
        // 获取请求头中的令牌
        String token = request.getHeader("Authorization");
        Long userId = jwtHelper.getUserId(token);

        //查询数据
        UserInfoVo userInfoVo = sysUserMapper.getUserInfo(userId);
        if (userInfoVo != null) {
            return Result.ok(userInfoVo);
        }

        return Result.build(null, ResultCodeEnum.USER_ERROR);
    }

    @Override
    public Result<UserInfoVo> getOtherInfo(String username) {
        SysUser user = this.getOne(
                new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, username));
        if (user == null) {
            return Result.build(null, ResultCodeEnum.USER_ERROR);
        }
        UserInfoVo userInfoVo = sysUserMapper.getUserInfo(user.getId());
        return Result.ok(userInfoVo);
    }

    @Override
    public PageResult<UserInfoVo> getUserInfoList(UserPageQuery userPageQuery) {
        Page<SysUser> userPage = new Page<>(userPageQuery.getPageNum(), userPageQuery.getPageSize());
        IPage<UserInfoVo> userInfoVoIPage = sysUserMapper.getUserPage(userPage, userPageQuery);
        return PageResult.success(userInfoVoIPage);
    }

    @Override
    public Result<String> updateUserInfo(ChangeUserInfoForm changeUserInfoForm) {
        SysUser user = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getId,changeUserInfoForm.getId()));
        if(user == null){
            return Result.build(null,ResultCodeEnum.USER_ERROR);
        }
        BeanUtils.copyProperties(changeUserInfoForm,user);
        sysUserMapper.updateById(user);
        return Result.ok(null,"修改成功");
    }

    @Override
    public Result<String> changeUserStatus(Long id,boolean isDisabled){
        SysUser user = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getId,id));
        if(user == null){
            return Result.build(null,ResultCodeEnum.USER_ERROR);
        }
        if(isDisabled){
            if(Objects.equals(user.getStatus(), ConstantEnum.STATUS_DISABLED.getValue())){
                return Result.build(null,500,"账号已停用中");
            }
            user.setStatus(ConstantEnum.STATUS_DISABLED.getValue());
            this.updateById(user);
            return Result.ok(null,"账号已成功停用");
        }else{
            if(Objects.equals(user.getStatus(), ConstantEnum.STATUS_NORMAL.getValue())){
                return Result.build(null,500,"账号正处于正常状态");
            }
            user.setStatus(ConstantEnum.STATUS_NORMAL.getValue());
            this.updateById(user);
            return Result.ok(null,"账号已恢复到正常状态");
        }
    }

    @Override
    public Result<String> changeUserDeleted(Long id,boolean isDeleted){
        SysUser user = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getId,id));
        if(user == null){
            return Result.build(null,ResultCodeEnum.USER_ERROR);
        }
        if(isDeleted){
            if(Objects.equals(user.getDeleted(), ConstantEnum.IS_DELETED.getValue())){
                return Result.build(null,500,"账号正处于删除状态");
            }
            this.removeById(user);
            return Result.ok(null,"账号成功删除");
        }else{
            if(Objects.equals(user.getDeleted(), ConstantEnum.NOT_DELETED.getValue())){
                return Result.build(null,500,"账号正处于使用状态");
            }
            user.setStatus(ConstantEnum.NOT_DELETED.getValue());
            this.updateById(user);
            return Result.ok(null,"账号成功恢复");
        }
    }

    @Override
    public Result<String> deleteMine(){
        // 获取请求头中的令牌
        String token = request.getHeader("Authorization");
        Long userId = jwtHelper.getUserId(token);
        SysUser user = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getId,userId));
        if(user == null){
            return Result.build(null,ResultCodeEnum.USER_ERROR);
        }
        if(Objects.equals(user.getStatus(), ConstantEnum.NOT_DELETED.getValue())){
            return Result.build(null,500,"账号未删除");
        }
        user.setStatus(ConstantEnum.NOT_DELETED.getValue());
        this.updateById(user);
        return Result.ok(null,"账号已恢复");
    }

    @Override
    public Result<String> resetUserPwd(Long id){
        SysUser user = sysUserMapper.selectById(id);
        if(user == null){
            return Result.build(null,ResultCodeEnum.USER_ERROR);
        }
        user.setPassword(MD5Util.encrypt("123456"));
        this.updateById(user);
        return Result.ok(null,"修改成功");
    }

    @Override
    public Result<String> updateUserPartInfo(String content,Boolean isAvatar,Boolean isSign){
        // 获取请求头中的令牌
        String token = request.getHeader("Authorization");
        Long userId = jwtHelper.getUserId(token);
        SysUser user = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getId,userId));
        if(user == null){
            return Result.build(null,ResultCodeEnum.USER_ERROR);
        }
        if(isAvatar) {
            this.update(new LambdaUpdateWrapper<SysUser>()
                    .eq(SysUser::getId,user.getId()).set(SysUser::getAvatar,content));
            return Result.ok(null,"成功更换头像");
        }
        if(isSign){
            this.update(new LambdaUpdateWrapper<SysUser>()
                    .eq(SysUser::getId,user.getId()).set(SysUser::getSign,content));
            return Result.ok(null,"成功更换标签");
        }
        return Result.build(null,ResultCodeEnum.SYSTEM_ERROR);
    }

}